// 引入axios
import axios from "axios"
import router from '../router'
// 引入querystring
import qsString from 'querystring'

axios.defaults.baseURL = "/api/"
// 设置请求拦截
axios.interceptors.request.use(req=>{
    if(req.url != 'userlogin'){
        req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')).token  : null
    }
    return req
})
// 设置响应拦截
axios.interceptors.response.use(res=>{
    if(res.data.msg=="请设置请求头,并携带验证字符串"){
        alert(res.data.msg)
        // 跳转登录页
        router.push('/login')
    }else if(res.data.msg=="登录已过期或访问权限受限"){
        alert(res.data.msg)
        // 跳转登录页
        router.push('/login')
    }else{
        return res.data
    }
    
})

/* 
    get请求封装
    url
    params
*/ 
export const get =(url,params={})=>{
    return new Promise((resolve,reject)=>{
        axios.get(url,{
            params
        })
        .then(res=>resolve(res))
        .catch(err=>reject(err))
    })
}

/*
    post请求封装
    url,
    params
    isFile 是否是上传文件
*/ 
export const post =(url,params={},isFile=false) =>{
    let data = {}
    if(isFile){
        data = new FormData()
        for(let i in params){
            data.append(i,params[i])
        }  
    }else{
        data = qsString.stringify(params)
    }
    return new Promise((resolve,reject)=>{
        axios.post(url,data)
        .then(res=>resolve(res))
        .catch(err=>reject(err))
    })
}
